package com.wy2.service.impl;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.wy2.entity.User;
import com.wy2.mapper.UserMapper;
import com.wy2.service.UserService;
import com.wy2.util.DateUtil;
import com.wy2.util.FenyeUtil;
import com.wy2.util.Md5Utils;
import com.wy2.util.QuanZhongUtil;
import com.wy2.util.SendMsg;
import com.wy2.util.TokenUtil;
@Service
public class UserServiceImpl implements UserService {
    // 注入用户Mapper
    @Autowired
    private UserMapper usersMapper;
    private Map<String, Object> maps = new HashMap<>();
    private String yzm = "";
	private String phonenum = "";
    /**
     * 用户登录
     */
    @Override
    public Map<String, Object> login(Map<String, Object> map) {
        String uname = (String) map.get("uname");
        String upassword = (String) map.get("upassword");
        System.out.println("登录名称=====" + uname);
        // 连接 数据库查询是否有当前用户
        User users = usersMapper.LoginByObj(uname);
        // 不为空 证明 用户存在
        if (users != null) {
            // 获取主键
            String uid = users.getUid();
            // 获取用户名
            String username = users.getUname();
            // 查看该用户是否已被锁定
            String islocked = users.getUislockout();
            // 获取当前的密码次数
            Integer daypwderrornum = users.getUpsdwrongtime();
            // 获取累计错误次数
            Integer uleijipwderrornum = users.getUleijipwderrornum();
            // 判断 ...
            if (uleijipwderrornum < 10) {
                // 判断 ...
                if ("否".equals(islocked) && daypwderrornum < 3) {
                    // 获取当前时间
                    String DayTime = DateUtil.getNow();
                    // 一切正常 可以登录
                    //将登录用户名作为盐
                    String salt = Md5Utils.salt(username);
                    System.out.println("生成的盐：========" + salt);
                    //再将盐+密码生成 加密后的密码
//                    String pwd = Md5Utils.md5(upassword);
                    String pwd = DigestUtils.md5DigestAsHex(upassword.getBytes());
                    System.out.println("最终加密后的密码：=======" + pwd);
                    // 获取用户密码 此处获取的是添加时候 盐+密码 生成的加密密码
                    String usersPassword = users.getUpassword();
                    System.out.println("数据库密码：=====" + usersPassword);
                    // 判断传过来的密码 是否 === 数据库存储的密码
                    if (pwd.equals(usersPassword)) {
                        // 如果相等  登录成功
                        map.put("success", true);
                        String time = DateUtil.getNow();
                        Integer times = usersMapper.dltime(uid,time);
                        // 重置当天密码错误次数
                        usersMapper.ResetDayErrorNum(uid);
                        //生成Token
                        String token = null;
                        try {
                            // 工具类生成Token
                            token = TokenUtil.sign(users, 1 * 60 * 60 * 1000); // 1 * 60 * 60 * 1000 = 1小时有效期
                            System.out.println("token=============" + token);
                        } catch (UnsupportedEncodingException |
                                JsonProcessingException e) {
                            e.printStackTrace();
                        }
                        map.put("uid", uid);
                        map.put("username", username);
                        map.put("token", token);
//                        map.put("rname", users.getRole());
//                        System.out.println("0000"+users.getRole());
                    } else {
                        // 否则 密码输入错误
                        daypwderrornum = daypwderrornum + 1;
                        uleijipwderrornum = uleijipwderrornum + 1;
                        // 修改密码错误次数
                        // 调用...
                        usersMapper.addOne(daypwderrornum, uname,uleijipwderrornum);
                        map.put("msg", "账户或密码输入错误");
                        if (daypwderrornum == 3) {
                            Integer res = usersMapper.Lockaccount(uid, DayTime);
                            map.put("msg", "您今天已累计错误3次，请明天在登陆");
                        }
                        if (uleijipwderrornum == 10) {
                            Integer res = usersMapper.Lockaccount(uid, DayTime);
                            map.put("msg", "您已累计错误10次，无法进行登录");
                        }
                    }
                } else {
                    map.put("msg", "您的账户已被锁定");
                }
            } else {
                map.put("msg", "您已累计错误10次，无法进行登录");
            }
        } else
            map.put("msg", "用户名不存在");
        return map;
    }
    
    
    @Override
	public FenyeUtil<User> getAll(FenyeUtil<User> fenye) {
		Integer count = usersMapper.getCount(fenye);
		List<User> data = usersMapper.getData(fenye);
		if(data.size()>0) {
			fenye.setCount(count);
			fenye.setData(data);
		}else {
			fenye.setCode(1);
			fenye.setMsg("无数据");
		}
		return fenye;
	}

    @Override
	public Integer addUser(User user) {
		// TODO Auto-generated method stub
		return usersMapper.addUser(user);
	}

	@Override
	public Integer updUser(User user) {
		// TODO Auto-generated method stub
		return usersMapper.updUser(user);
	}

	@Override
	public Integer delUser(String uid) {
		return usersMapper.delUser(uid);
	}
	@Override
	public List<User> newPass(String uid) {
		// TODO Auto-generated method stub
		return usersMapper.findByUid(uid);
	}

	@Override
	public Integer updateNodid(String b, String uid) {
		// TODO Auto-generated method stub
		return usersMapper.updateNodid(b,uid);
	}

	@Override
	public int upisLockFalse(String uid) {
		// TODO Auto-generated method stub
		return usersMapper.upisLockFalse(uid);
	}

	@Override
	public int upisLockTrue(String uid) {
		// TODO Auto-generated method stub
		return usersMapper.upisLockTrue(uid);
	}


	@Override
	public Object selectPwd(String uname, String upasswordl) {
		// TODO Auto-generated method stub
		return usersMapper.selectPwd(uname,upasswordl);
	}


	@Override
	public Integer updPwd(String uname, String xpassl) {
		// TODO Auto-generated method stub
		return usersMapper.updPwd(uname,xpassl) != 0 ? 1 : 0;
	}


	@Override
	public Map<String, Object> findPhone(String uprotectmetl) {
		Map<String, Object> map = new HashMap<>();
		User users = usersMapper.findPhone(uprotectmetl);
		if(users == null) {
			map.put("code", 0);
			map.put("msg", "请输入正确手机号");
		} else {
			map.put("code", 1);
			map.put("msg", "有该手机号");
			phonenum = uprotectmetl;
			System.out.println("全局手机号"+phonenum);
			yzm = SendMsg.getCode();
			System.out.println("全局验证码"+yzm);
		}
		return map;
	}


	@Override
	public Map<String, Object> findPassword(String yzm, String uidcard, String pwd, String xpass2) {
		Map<String, Object> map = new HashMap<>();
		User users = usersMapper.findIdentity(uidcard);
		if(users == null) {
			map.put("code", 0);
			map.put("msg", "请输入身份证号");
		} else {
			map.put("code", 1);
			map.put("msg", "有身份证号");
			usersMapper.findPassword(xpass2,uidcard);
		}
		return map;
	}


	@Override
	public List<User> UserCard(String uidcard) {
		// TODO Auto-generated method stub
		return usersMapper.UserCard(uidcard);
	}


	@Override
	public List<User> UserEmail(String uprotectemail) {
		// TODO Auto-generated method stub
		return usersMapper.UserEmail(uprotectemail);
	}


	@Override
	public List<User> UserMetl(String uprotectmetl) {
		// TODO Auto-generated method stub
		return usersMapper.UserMetl(uprotectmetl);
	}


	@Override
	public Integer islocl(User user) {
		// TODO Auto-generated method stub
		return usersMapper.islocl(user);
	}


	@Override
	public User getByUidUname(String uid) {
		// TODO Auto-generated method stub
		return usersMapper.getByUidUname(uid);
	}


	@Override
	public FenyeUtil<QuanZhongUtil> getQz(FenyeUtil<QuanZhongUtil> fenye) {
		Integer count = usersMapper.getCountByQz(fenye);
		List<QuanZhongUtil> data = usersMapper.getDataByQz(fenye);
		
		if(data.size()>0) {
			fenye.setCount(count);
			fenye.setData(data);
		}else {
			fenye.setCode(1);
			fenye.setMsg("无数据");
		}
		return fenye;
	}


	@Override
	public List<QuanZhongUtil> findByIntime(String times) {
		// TODO Auto-generated method stub
		System.out.println("--timesimpl--"+times);
		return usersMapper.findByIntime(times);
	}


	@Override
	public Integer updQz(QuanZhongUtil qz) {
		// TODO Auto-generated method stub
		return usersMapper.updQz(qz);
	}








	




	

    
}
